package com.chatim.nonamechatim.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
import io.netty.channel.nio.NioEventLoopGroup;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Slf4j
public class ServerBoot {

    @Resource
    ServerBootstrap serverBootstrap;

    @Resource
    NioEventLoopGroup boosGroup;

    @Resource
    NioEventLoopGroup workerGroup;

    @Resource
    NettyProperties nettyProperties;

    // 所有连接上来的用户
    public static final Map<Long, Channel> USERLIST = new ConcurrentHashMap<>(1024);
    // ChannelID和用户ID的映射
    public static final Map<ChannelId, Long> CHANNELUSER = new ConcurrentHashMap<>(1024);

    /**
     * 开机启动
     */
    @PostConstruct
    public void start() throws InterruptedException {
        // 绑定端口启动
        serverBootstrap.bind(nettyProperties.getPort()).sync();
        serverBootstrap.bind(nettyProperties.getPortSalve()).sync();
        log.info("启动Netty多端口服务器: {},{}",nettyProperties.getPort(),nettyProperties.getPortSalve());
    }

    /**
     * 关闭线程池
     */
    @PreDestroy
    public void close(){
        log.info("关闭Netty服务器");
        boosGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}


